#!/bin/bash

# Check if a filename is provided
if [ $# -ne 1 ]; then
    echo "Usage: $0 <filename>"
    exit 1
fi

filename="$1"

# Check if file exists
if [ ! -f "$filename" ]; then
    echo "Error: File '$filename' does not exist."
    exit 1
fi

# Get file extension (lowercase)
ext="${filename##*.}"
ext="${ext,,}"  # Convert to lowercase

# Get base filename (without path)
base_name=$(basename "$filename")

# Determine comment style and header line
case "$ext" in
    c|h|cpp|cxx|hpp|cc)
        # C/C++ style (// comments)
        header="// filename: $base_name"
        ;;
    py)
        # Python style (# comments)
        header="# filename: $base_name"
        ;;
    sh|bash)
        # Shell script style (# comments)
        header="# filename: $base_name"
        ;;
    js|ts|jsx|tsx)
        # JavaScript/TypeScript style (// comments)
        header="// filename: $base_name"
        ;;
    html|xml)
        # HTML/XML style (<!-- --> comments)
        header="<!-- filename: $base_name -->"
        ;;
    java)
        # Java style (// comments)
        header="// filename: $base_name"
        ;;
    rb)
        # Ruby style (# comments)
        header="# filename: $base_name"
        ;;
    php)
        # PHP style (// comments)
        header="// filename: $base_name"
        ;;
    *)
        # Default to # comments for unknown types
        header="# filename: $base_name"
        echo "Warning: Unknown extension '$ext' - using default comment style"
        ;;
esac

# Check if header already exists (to avoid duplicates)
if grep -qxF "$header" "$filename"; then
    echo "Header already exists in '$filename'"
    exit 0
fi

# Add header to top of file using temporary file
temp_file=$(mktemp)
echo "$header" > "$temp_file"
cat "$filename" >> "$temp_file"
mv "$temp_file" "$filename"

echo "Added header to '$filename':"
echo "$header"
